﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.UI.Main.Widget;
using UniRlv.Utility;
using UniRlv.Utility.Extend;

namespace UniRlv.UI.Main.BasicInfo
{
    public partial class FrmProductInfo : UniRlv.UI.Main.FrmBase
    {
        BindingList<ProductInfo> details = new BindingList<ProductInfo>();
        int total = 0;

        public FrmProductInfo()
        {
            InitializeComponent();
        }

        private void FrmProductInfo_Load(object sender, EventArgs e)
        {
            #region 初始化工具栏

            toolBtnModify.Visible = true;
            toolBtnSync.Visible = true;
            toolBtnAdd.Visible = true;
            toolBtnImport.Visible = true;
            toolBtnDelete.Visible = true;
            toolBtnQuery.Visible = true;

            toolBtnAdd.Click += toolBtnAdd_Click;
            toolBtnDelete.Click += toolBtnDelete_Click;
            toolBtnModify.Click += toolBtnModify_Click;
            toolBtnSync.Click += toolBtnSync_Click;
            toolBtnImport.Click += toolBtnImport_Click;
            toolBtnQuery.Click += toolBtnQuery_Click;

            ToolStripButton btnEditPackage = AddToolButton("packageEdit", "编辑产品包装");
            btnEditPackage.Click += btnEditPackage_Click;
            
            #endregion

            #region 初始化DataGridView和数据源

            UIHelper.InitDataGridView(dgvDetails);

            dgvDetails.DataSource = details;

            #endregion

            if (this.Tag != null)
            {
                ProductInfo info = this.Tag as ProductInfo;
                txtTYM.Text = info.tym;
            }
            toolLstPage.Text = ConfigurationHelper.AppGetString("page");
        }

        void toolBtnQuery_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void RefreshData()
        {
            string msg = string.Empty;

            details.Clear();

            try
            {
                if (string.IsNullOrEmpty(txtTYM.Text))
                {
                    total = DALOpr.QueryWholeQuantity<ProductInfo>(ref msg);
                }
                else
                {
                    string whereString = string.Format("tym like '%{0}%'", txtTYM.Text);
                    total = DALOpr.QueryLimitQuantity<ProductInfo>(whereString, ref msg);
                }

                
                int pageSize = Convert.ToInt32(toolLstPage.Text);

                if (total > 0)
                {
                    toolTxtPage.Text = "1";
                    toolTxtTip.Text = string.Format("页 共{0}页，{1}条记录", (total - 1) / pageSize + 1, total);

                    toolBtnReload.PerformClick();
 
                    
                }
                else
                {
                    toolTxtPage.Text = "0";
                    toolTxtTip.Text = string.Format("页 共0页，0条记录");
                }

            }
            catch (Exception exp)
            {
                ShowErrorMessageBox(exp);
            }

        }
         
        #region 工具栏事件响应

        void btnEditPackage_Click(object sender, EventArgs e)
        {//跳转到包装界面
            if (dgvDetails.CurrentRow != null)
            {
                ProductInfo p = dgvDetails.CurrentRow.DataBoundItem as ProductInfo;
                FrmMain.GetInstance().SwitchFormByModuleName("PackageInfo", p);
            }
            else
            {
                ShowInfoMessageBox("提示", "先选择需要编辑包装信息的产品");
            }

        }

        void toolBtnImport_Click(object sender, EventArgs e)
        {
            
        }

        void toolBtnSync_Click(object sender, EventArgs e)
        {
            FrmRadioButtonSelect frm = new FrmRadioButtonSelect();
            frm.Text = "请选择同步策略";
            frm.Tip = "同步策略";
            frm.Values = new string[] { "追加", "覆盖（删除原有）"};

            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                if (string.IsNullOrEmpty(PublicObject.CurCompany.companyID))
                {
                    MessageBox.Show("企业ID不能为空，请先同步企业信息");
                    return;
                }

                try
                {
                    Wait();
                    //查询所有当前产品
                    
                    var info = SyzsAsync.SyzsInfoAsync.GetProductInfo(PublicObject.CurCompany.companyID);
                    List<ProductInfo> syncProducts = new List<ProductInfo>();
                    ProductInfo p;
                    string sql;
                    string msg = string.Empty;

                    txtTYM.Text = string.Empty;//防止加载数据时添加此查询条件

                    foreach (var item in info)
                    {
                        p = new ProductInfo();
                        p.company = PublicObject.CurCompany.name;
                        p.createTime = DateTime.Now;
                        p.creator = PublicObject.CurUser.name;
                        p.gg = item.gg.Trim();
                        p.itemid = item.itemid;
                        p.pzrq = Convert.ToDateTime(item.pzrq);
                        p.pzwh = item.pzwh;
                        p.spm = item.spm.Trim();
                        p.state = 1;
                        p.tym = item.tym;
                        p.yxq = 1;
                        p.yxqdw = 1;
                        syncProducts.Add(p);
                    }

                    if (syncProducts == null || syncProducts.Count == 0)
                    {
                        ShowWarnningMessageBox("提示", "未同步到任何产品信息！");
                        WaitBack();
                        return;
                    }

                    msg = string.Empty;
                    List<ProductInfo> allPrducts = DALOpr.QueryAll<ProductInfo>(ref msg);

                    if (frm.CurSelect == 0 && allPrducts != null && allPrducts.Count>0)
                    {//追加
                        List<ProductInfo> toAdd = new List<ProductInfo>(), toUpdate = new List<ProductInfo>();

                        foreach (var item in syncProducts)
                        {
                            int idx = allPrducts.IndexOf(item);
                            
 
                            if (idx>=0)
                            {
                                p = allPrducts[idx];

                                item.ID = p.ID;
                                item.cname = p.cname;
                                item.remarks = p.remarks;
                                item.createTime = p.createTime;
                                item.state = p.state;
                                item.weight = p.weight;
                                item.yxq = p.yxq;
                                item.yxqdw = p.yxqdw;
                                toUpdate.Add(item);
                            }
                            else
                            {
                                toAdd.Add(item);
                            }
                        }

                        msg = string.Format("一共同步到{0}件产品信息，当前已有产品{1}件，即将新添加{2}件产品，更新{3}件产品，是否确认追加？", syncProducts.Count, total, toAdd.Count, toUpdate.Count);

                        if (MessageBox.Show(this, msg, "请确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                        {
                            int cnt = 0;
                            int steps = 50;
                            bool bRes = true;

                            while (cnt < toAdd.Count)
                            {
                                sql = string.Empty;
                                for (int i = cnt; i < cnt + steps && i < toAdd.Count; i++)
                                {
                                    sql += "|";
                                    sql += EntityHelper.GetInsertSql(toAdd[i]);
                                    cnt++;
                                }

                                sql = sql.Substring(1);
                                msg = string.Empty;

                                bRes &= DALOpr.ExecuteNonQueryTran(sql, ref msg);
                            }

                            while (cnt < toUpdate.Count)
                            {
                                sql = string.Empty;
                                for (int i = cnt; i < cnt + steps && i < toUpdate.Count; i++)
                                {
                                    sql += "|";
                                    sql += EntityHelper.GetUpdateSql(toUpdate[i]);
                                    cnt++;
                                }

                                sql = sql.Substring(1);
                                msg = string.Empty;

                                bRes &= DALOpr.ExecuteNonQueryTran(sql, ref msg);
                            }

                            if (bRes)
                            {
                                RefreshData();
                                MessageBox.Show("同步完成！");
                            }
                            else
                            {
                                ShowErrorMessageBox("出现错误", msg);
                            }
                        }
                    }
                    else
                    {//覆盖
                        //删除所有产品、包装关系

                        msg = string.Format("一共同步到{0}件产品信息，当前已有产品{1}件，一旦确认将覆盖当前所有产品信息并删除所有包装信息，是否确认覆盖？", syncProducts.Count, total);

                        if (MessageBox.Show(this, msg, "请确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                        {
                            sql = "delete from PackageRule|delete from PackageDetail|delete from ProductInfo";
                            msg = string.Empty;
                            bool bRes = true;

                            if (DALOpr.ExecuteNonQueryTran(sql, ref msg))
                            {
                                
                                int cnt = 0;
                                int steps = 50;

                                while (cnt<syncProducts.Count)
                                {
                                    sql = string.Empty;
                                    for (int i = cnt; i < cnt + steps && i < syncProducts.Count; i++)
                                    {
                                        sql += "|";
                                        sql += EntityHelper.GetInsertSql(syncProducts[i]);
                                        cnt++;
                                    }

                                    sql = sql.Substring(1);
                                    msg = string.Empty;

                                    bRes &= DALOpr.ExecuteNonQueryTran(sql, ref msg);
                                }

                                details.Clear();

                                if (bRes)
                                {
                                    RefreshData();
                                    MessageBox.Show("同步完成！");
                                }
                                else
                                {
                                    ShowErrorMessageBox("出现错误", msg);
                                }
                            }
                            else
                            {
                                ShowErrorMessageBox("清除产品信息和包装出错", msg);
                            }
                        }
                        
                    }
                    WaitBack();
                }
                catch (Exception exp)
                {
                    ShowErrorMessageBox(exp);
                }
            }
        }

        void toolBtnModify_Click(object sender, EventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                ProductInfo p = dgvDetails.CurrentRow.DataBoundItem as ProductInfo;
                FrmAddOrEditProduct frm = new FrmAddOrEditProduct();
                frm.Tag = p;
                frm.Text = "修改产品信息";
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    p = frm.Tag as ProductInfo;
                    string sql = EntityHelper.GetUpdateSql(p);
                    string msg = string.Empty;

                    if (DALOpr.ExecuteNonQuery(sql, ref msg))
                    {
                        int idx = details.IndexOf(p);
                        details.RemoveAt(idx);
                        details.Insert(idx, p);

                        dgvDetails.SetRowSelect(idx);

                        ShowInfoMessageBox("提示", "修改成功");
                    }
                    else
                    {
                        ShowErrorMessageBox("修改失败", msg);
                    }
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "先选择需要修改的记录");
            }
        }

        void toolBtnDelete_Click(object sender, EventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                ProductInfo p = dgvDetails.CurrentRow.DataBoundItem as ProductInfo;

                if (ShowConfirmDialog("请确认", "确定要删除该记录？\r\n" + p.ToString()) == System.Windows.Forms.DialogResult.OK)
                {
                    string sql = "delete from ProductInfo where id = " + p.ID;
                    string msg = string.Empty;

                    if (DALOpr.ExecuteNonQuery(sql, ref msg))
                    {
                        details.Remove(p);
                    }
                    else
                    {
                        ShowErrorMessageBox("删除失败", msg);
                    }
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "先选择需要删除的记录");
            }
        }

        void toolBtnAdd_Click(object sender, EventArgs e)
        {
            FrmAddOrEditProduct frm = new FrmAddOrEditProduct();
            frm.Text = "添加产品信息";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ProductInfo p = frm.Tag as ProductInfo;
                string msg = string.Empty;

                //2021-09-15注释  政府专供产品，产品名称是一样的，通用名不同
                //if (details.Contains(p))
                //{
                //    ShowWarnningMessageBox("警告", "不允许添加同名和同文号的产品");
                //    return;
                //}

                if (DALOpr.Insert(p, ref msg))
                {
                    details.Add(p);

                    dgvDetails.SetRowSelect(details.Count-1);
                    ShowInfoMessageBox("提示", "添加成功");
                }
                else
                {
                    ShowErrorMessageBox("添加失败", msg);
                }
            }
        }
        #endregion

        #region 分页响应


        private void toolBtnFirst_Click(object sender, EventArgs e)
        {
            txtTYM.Text = "";
            if (total>0 && toolTxtPage.Text != "1")
            {
                toolTxtPage.Text = "1";
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnPrevious_Click(object sender, EventArgs e)
        {
            int page = Convert.ToInt32(toolTxtPage.Text);
            txtTYM.Text = "";
            if (total > 0 && page > 1)
            {
                toolTxtPage.Text = (page-1).ToString();
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnNext_Click(object sender, EventArgs e)
        {
            int pageSize = Convert.ToInt32(toolLstPage.Text);
            int pages = total / pageSize + 1;
            int curPage = Convert.ToInt32(toolTxtPage.Text);

            txtTYM.Text = "";
            if (curPage<pages)
            {
                toolTxtPage.Text = (curPage + 1).ToString();
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnLast_Click(object sender, EventArgs e)
        {
            int pageSize = Convert.ToInt32(toolLstPage.Text);
            int pages = total / pageSize + 1;
            int curPage = Convert.ToInt32(toolTxtPage.Text);

            txtTYM.Text = "";
            if (curPage != pages)
            {
                toolTxtPage.Text = pages.ToString();
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnReload_Click(object sender, EventArgs e)
        {
            Wait();

            int page = Convert.ToInt32(toolTxtPage.Text);
            int pageSize = Convert.ToInt32(toolLstPage.Text);
            string msg = string.Empty;
            List<ProductInfo> li;

            if (string.IsNullOrEmpty(txtTYM.Text))
            {
                li = DALOpr.QueryPage<ProductInfo>(page, pageSize, ref msg);
            }
            else
            {
                string whereString = string.Format("tym like '%{0}%'", txtTYM.Text);
                li = DALOpr.QueryPage<ProductInfo>(page, pageSize, whereString, ref msg);
            }
            

            if (string.IsNullOrEmpty(msg))
            {
                details.Clear();
                dgvDetails.Tag = (page - 1) * pageSize;

                if (li!=null)
                {
                    foreach (var item in li)
                    {
                        details.Add(item);
                    }
                }
                else
                {
                    total = 0;
                    toolTxtPage.Text = "0";
                    toolTxtTip.Text = string.Format("页 共0页，0条记录");
                }
            }
            else
            {
                ShowErrorMessageBox("出现错误", msg);
            }

            WaitBack();
        }

        private void toolTxtPage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!AppHelper.IsInteger(toolTxtPage.Text))
                {
                    ShowWarnningMessageBox("请注意", "请输入整数！");
                    toolTxtPage.Focus();
                    toolTxtPage.SelectAll();
                }
                else
                {
                    toolBtnReload.PerformClick();
                }
            }
        }

        private void toolLstPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            ConfigurationHelper.AppSet("page", toolLstPage.Text);
            RefreshData();
        }

        #endregion

        private void dgvDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                toolBtnModify.PerformClick();
            }
        }

        private void txtTYM_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                RefreshData();
            }
        }

        private void dgvDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                ProductInfo p = dgvDetails.CurrentRow.DataBoundItem as ProductInfo;
                txtTYM.Text = p.tym;
            }
        }

    }
}
